package com.qjdchina.sku.front.web.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.qjdchina.sku.model.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.PictureData;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.qjdchina.common.web.util.RestBody;
import com.qjdchina.commons.model.PageModel;
import com.qjdchina.commons.result.Result;
import com.qjdchina.sku.adaptor.ProductDaoAdaptor;
import com.qjdchina.sku.biz.BrandManager;
import com.qjdchina.sku.biz.CategoryManager;
import com.qjdchina.sku.biz.ProductPictureManager;
import com.qjdchina.sku.biz.RolePriceManager;
import com.qjdchina.sku.biz.SkuCompanyManager;
import com.qjdchina.sku.biz.SkuItemManager;
import com.qjdchina.sku.biz.SkuProductManager;
import com.qjdchina.sku.biz.UserRoleManager;
import com.qjdchina.sku.consts.WebConsts;
import com.qjdchina.sku.converter.ProductPictureConverter;
import com.qjdchina.sku.converter.SkuProductConverter;
import com.qjdchina.sku.enums.AuditStatus;
import com.qjdchina.sku.enums.IsRequired;
import com.qjdchina.sku.enums.UserType;
import com.qjdchina.sku.model.query.SkuProductQueryVO;
import com.qjdchina.sku.model.vo.BrandBasicVO;
import com.qjdchina.sku.model.vo.BrandVO;
import com.qjdchina.sku.model.vo.MongoSkuProductVO;
import com.qjdchina.sku.model.vo.ProductPictureVO;
import com.qjdchina.sku.model.vo.SkuBasicVO;
import com.qjdchina.sku.model.vo.SkuCompanyVO;
import com.qjdchina.sku.model.vo.SkuItemAttributeVO;
import com.qjdchina.sku.model.vo.SkuItemBasicVO;
import com.qjdchina.sku.model.vo.SkuItemVO;
import com.qjdchina.sku.model.vo.SkuProductCompareVO;
import com.qjdchina.sku.model.vo.SkuProductDetailVO;
import com.qjdchina.sku.model.vo.SkuProductVO;
import com.qjdchina.sku.service.enums.SkuResultCode;
import com.qjdchina.sku.util.ProductToExcel;
import com.qjdchina.sku.util.ReadExcelUtil;

/**
 * 部品
 * 
 * @author shenpingfeng 2016年11月24日
 */
@Controller
@RequestMapping(value = "product")
public class ProductController {

	public static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class);
	@Autowired
	private SkuItemManager skuItemManager;
	@Autowired
	private BrandManager brandManager;
	@Autowired
	private SkuProductManager skuProductManager;
	@Autowired
	private ProductPictureManager productPictureManager;
	@Autowired
	private ProductDaoAdaptor productDaoAdaptor;
	@Autowired
	private UserRoleManager userRoleManager;
	@Autowired
	private RolePriceManager rolePriceManager;

	@Autowired
	private CategoryManager categoryManager;
	@Autowired
	private SkuCompanyManager skuCompanyManager;

	/**
	 * 根据条件查询 shenpingfeng 2016年12月1日
	 * 
	 * @param skuProductQueryVO
	 * @param strPage
	 * @return
	 */
	@RequestMapping(value = "query", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<PageModel<SkuProductVO>> query(SkuProductQueryVO skuProductQueryVO,
			@RequestParam(value = "pageNo", required = false) String strPage, HttpServletRequest request) {
		HttpSession session = request.getSession();
		// 获取用户类型,如果不是集团的，就查询自己的信息

		String userType = (String) session.getAttribute(WebConsts.USER_TYPE);
		if (!userType.equals(UserType.GROUP.getValue())) {
			Integer companyId = (Integer) session.getAttribute(WebConsts.COMPANY_ID);
			skuProductQueryVO.setCompanyId(companyId);
		} else {
			// 如果是集团的,查看初审通过，审核通过,审批驳回的产品
			String auditStatus = skuProductQueryVO.getAuditStatus();
			if (StringUtils.isBlank(auditStatus)) {
				List<String> auditStatusList = new ArrayList<String>();
				auditStatusList.add(AuditStatus.TRIAL_PASS.getValue());
				auditStatusList.add(AuditStatus.AUDITPASS.getValue());
				auditStatusList.add(AuditStatus.REJECT.getValue());
				skuProductQueryVO.setAuditStatusList(auditStatusList);
			}

		}
		String auditTimeEnd = skuProductQueryVO.getAuditTimeEnd();
		if (StringUtils.isNotBlank(auditTimeEnd)) {
			DateTime dateTime = new DateTime(auditTimeEnd);
			String endTime = dateTime.dayOfYear().addToCopy(1).toString("yyyy-MM-dd");
			skuProductQueryVO.setAuditTimeEnd(endTime);
		}

		PageModel<SkuProductVO> pageModel = new PageModel<SkuProductVO>();
		int pageNo = 1;
		if (StringUtils.isNotEmpty(strPage) && StringUtils.isNumeric(strPage)) {
			pageNo = Integer.parseInt(strPage);
		}
		pageModel.setPageNo(pageNo);
		pageModel.setPageSize(15);
		Result<PageModel<SkuProductVO>> result = skuProductManager.queryPagedProductList(skuProductQueryVO, pageModel);
		if (!result.isSuccess()) {
			return new RestBody<PageModel<SkuProductVO>>(result.getCode(), result.getMessage());
		}
		PageModel<SkuProductVO> pageSkuProduct = result.getDataModel();

		return new RestBody<PageModel<SkuProductVO>>(SkuResultCode.SUCCESS, pageSkuProduct);

	}

	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public RestBody<SkuBasicVO> list(SkuProductQueryVO skuProductQueryVO,
			@RequestParam(value = "skuInfo", required = false) String skuInfo,
			@RequestParam(value = "pageNo", required = false) String strPage,
			@RequestParam(value = "pageSize", required = false) Integer pageSize, HttpServletRequest request) {

		Result<List<Integer>> resultSkuRoleId = getSkuRoleId(request);
		if (!resultSkuRoleId.isSuccess()) {
			return new RestBody<SkuBasicVO>(resultSkuRoleId.getCode(), resultSkuRoleId.getMessage());
		}
		List<Integer> skuRoleIds = resultSkuRoleId.getDataModel();
		// 目前角色只关联一个，取值第一个
		Integer skuRoleId = skuRoleIds.get(0);
		Result<RolePrice> resultRolePrice = getRolePrice(skuRoleId);

		if (!resultRolePrice.isSuccess()) {
			return new RestBody<SkuBasicVO>(resultRolePrice.getCode(), resultRolePrice.getMessage());
		}
		RolePrice rolePrice = resultRolePrice.getDataModel();

		if (skuProductQueryVO == null || skuProductQueryVO.getSkuCategoryId() == null) {
			return new RestBody<SkuBasicVO>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		Integer skuCategoryId = skuProductQueryVO.getSkuCategoryId();
		skuProductQueryVO.setAuditStatus(AuditStatus.AUDITPASS.getValue());

		Result<List<BrandVO>> resultBrandVO = brandManager.getBrandByCategoryId(skuCategoryId, skuRoleIds, null);
		Result<Map<String, Object>> resultSkuItemBasicVO = skuItemManager.getSkuByCategoryId(skuCategoryId);
		if (!resultSkuItemBasicVO.isSuccess() && !SkuResultCode.DATA_NOT_EXIST.getCode().equals(resultSkuItemBasicVO.getCode())) {
			return new RestBody<SkuBasicVO>(resultSkuItemBasicVO.getCode(), resultSkuItemBasicVO.getMessage());
		}

		List<BrandVO> brandVOs = resultBrandVO.getDataModel();
		List<Integer> brandIds = new ArrayList<Integer>();
		if (brandVOs != null && brandVOs.size() > 0) {
			for (BrandVO brandVO : brandVOs) {
				brandIds.add(brandVO.getId());
			}
		}
		skuProductQueryVO.setBrandIds(brandIds);
		List<SkuItemBasicVO> skuItemBasicVOs = new ArrayList<>();
		if (resultSkuItemBasicVO.getDataModel() != null) {
			skuItemBasicVOs = (List<SkuItemBasicVO>) resultSkuItemBasicVO.getDataModel().get("skuItemBasicVOs");
		}

		PageModel<SkuProductVO> pageModel = new PageModel<SkuProductVO>();
		int pageNo = 1;
		if (StringUtils.isNotEmpty(strPage) && StringUtils.isNumeric(strPage)) {
			pageNo = Integer.parseInt(strPage);
		}
		pageModel.setPageNo(pageNo);
		if (pageSize == null) {
			pageSize = 12;
		}
		pageModel.setPageSize(pageSize);

		List<SkuItemAttributeVO> skuItemAttributeVOs = JSON.parseArray(skuInfo, SkuItemAttributeVO.class);
		skuProductQueryVO.setSkuItemAttributeVOs(skuItemAttributeVOs);
		Result<PageModel<SkuProductVO>> result = skuProductManager.pageQueryProduct(skuProductQueryVO, pageModel);

		BrandBasicVO brandBasicVO = new BrandBasicVO();
		brandBasicVO.setName("品牌");
		brandBasicVO.setBrandVOs(brandVOs);

		SkuBasicVO skuBasicVO = new SkuBasicVO();
		skuBasicVO.setBrandBasicVO(brandBasicVO);
		skuBasicVO.setSkuItemBasicVOs(skuItemBasicVOs);

		if (result.isSuccess()) {
			List<SkuProductVO> skuProductVOs = result.getDataModel().getPagedRecords();
			for (SkuProductVO skuProductVO : skuProductVOs) {
				if (rolePrice.getIsShow().equals("1")) {
					skuProductVO.setDisplayPrice("****");
				} else {
					String priceStr = skuProductVO.getStrategicPrice() == null ? "0" : skuProductVO.getStrategicPrice().toString();
					skuProductVO.setDisplayPrice(priceStr);
				}
			}

			PageModel<SkuProductVO> skuProductVO = result.getDataModel();
			skuBasicVO.setSkuProducts(skuProductVO);
		} else {
			skuBasicVO.setSkuProducts(pageModel);
		}

		return new RestBody<SkuBasicVO>(SkuResultCode.SUCCESS, skuBasicVO);

	}

	/**
	 * 产品比较
	 * 
	 * @return
	 */
	@RequestMapping(value = "compare", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<SkuProductCompareVO> productCompare(@RequestParam(required = true) Integer[] ids,
			HttpServletRequest request) {
		Result<List<Integer>> resultSkuRoleId = getSkuRoleId(request);
		if (!resultSkuRoleId.isSuccess()) {
			return new RestBody<SkuProductCompareVO>(resultSkuRoleId.getCode(), resultSkuRoleId.getMessage());
		}
		List<Integer> skuRoleIds = resultSkuRoleId.getDataModel();
		// 目前角色只关联一个，取值第一个
		Integer skuRoleId = skuRoleIds.get(0);
		Result<RolePrice> resultRolePrice = getRolePrice(skuRoleId);

		if (!resultRolePrice.isSuccess()) {
			return new RestBody<SkuProductCompareVO>(resultRolePrice.getCode(), resultRolePrice.getMessage());
		}
		RolePrice rolePrice = resultRolePrice.getDataModel();

		Result<SkuProductCompareVO> skuProductCompareVOResult = skuProductManager.productCompare(ids, rolePrice);
		if (!skuProductCompareVOResult.isSuccess()) {
			LOGGER.warn("product compare fail !");
			return new RestBody<SkuProductCompareVO>(skuProductCompareVOResult.getResultCode());
		}

		return new RestBody<SkuProductCompareVO>(SkuResultCode.SUCCESS, skuProductCompareVOResult.getDataModel());
	}

	/**
	 * 产品信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "info", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<SkuProductCompareVO> productInfo(@RequestParam(required = true) Integer id,
			HttpServletRequest request) {

		Result<List<Integer>> resultSkuRoleId = getSkuRoleId(request);
		if (!resultSkuRoleId.isSuccess()) {
			return new RestBody<SkuProductCompareVO>(resultSkuRoleId.getCode(), resultSkuRoleId.getMessage());
		}
		List<Integer> skuRoleIds = resultSkuRoleId.getDataModel();
		// 目前角色只关联一个，取值第一个
		Integer skuRoleId = skuRoleIds.get(0);
		Result<RolePrice> resultRolePrice = getRolePrice(skuRoleId);

		if (!resultRolePrice.isSuccess()) {
			return new RestBody<SkuProductCompareVO>(resultRolePrice.getCode(), resultRolePrice.getMessage());
		}
		RolePrice rolePrice = resultRolePrice.getDataModel();

		Integer[] ids = new Integer[1];
		ids[0] = id;

		Result<SkuProductCompareVO> skuProductVOResult = skuProductManager.productCompare(ids, rolePrice);
		if (!skuProductVOResult.isSuccess()) {
			LOGGER.warn("query product info fail !");
			return new RestBody<SkuProductCompareVO>(skuProductVOResult.getResultCode());
		}

		return new RestBody<SkuProductCompareVO>(SkuResultCode.SUCCESS, skuProductVOResult.getDataModel());
	}

	/**
	 * 文件上传 shenpingfeng 2016年12月1日
	 * 
	 * @param file
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<Map<String, String>> upload(MultipartFile file, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<String, String> map = new HashMap<String, String>();

		try {
			Result<String> result = skuProductManager.saveUploadedFileUpdate(file);
			map.put("picturePath", result.getDataModel());

		} catch (Exception e) {
			LOGGER.error("upload exception {}", e);
			return new RestBody<Map<String, String>>(SkuResultCode.DATA_ERROR);
		}

		return new RestBody<Map<String, String>>(SkuResultCode.SUCCESS, map);
	}

	@RequestMapping(value = "uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> upload(@RequestParam(value = "file", required = false) MultipartFile file, String action,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, String> retMap = new HashMap<>();
		Result<String> result = skuProductManager.saveUploadedFileUpdate(file);
		String key = result.getDataModel();
		String retUrl = "/sku/front/product/loadFile?buzKey=" + key;
		retMap.put("url", retUrl);
		// retMap.put("title", retUrl);
		// retMap.put("original", retUrl);
		retMap.put("state", "SUCCESS");

		return retMap;

	}

	@RequestMapping(value = "uploadImg", method = RequestMethod.GET)
	@ResponseBody
	public String upload(String action, HttpServletRequest request, HttpServletResponse response, Model model) {
		String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
		String projectPath = nodepath.substring(1, nodepath.length() - 16);
		String filePath = "/" + projectPath + "static/config.json";
		String data = ReadFile(filePath);
		LOGGER.info("date {}", data);
		return data;
	}

	/**
	 * 查询产品详情 shenpingfeng 2016年12月1日
	 * 
	 * @param productId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "productDetail", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<SkuProductDetailVO> productDetail(
			@RequestParam(value = "productId", required = true) Integer productId, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		SkuProductDetailVO skuProductDetailVO = null;
		try {

			Result<SkuProductDetailVO> result = skuProductManager.findProductDetailByProdcutId(productId, response);
			if (!result.isSuccess()) {
				return new RestBody<SkuProductDetailVO>(result.getCode(), result.getMessage());
			}
			skuProductDetailVO = result.getDataModel();

		} catch (Exception e) {
			LOGGER.error("productDetail Exception{}", e);
			return new RestBody<SkuProductDetailVO>(SkuResultCode.SYS_EXCEPTION);
		}

		return new RestBody<SkuProductDetailVO>(SkuResultCode.SUCCESS, skuProductDetailVO);
	}

	/**
	 * 读取图片 shenpingfeng 2017年2月9日
	 * 
	 * @param buzKey
	 * @param model
	 * @param response
	 */
	@RequestMapping(value = "loadFile", method = RequestMethod.GET)
	public void loadFile(@RequestParam(value = "buzKey", required = true) String buzKey, Model model,
			HttpServletResponse response) {
		Result<File> result = skuProductManager.loadUploadedFileUpdate(buzKey, response);
		if (!result.isSuccess()) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("loadFile fail:", result.getResultCode().getMessage());
			}
		}
	}

	/**
	 * 创建部品 shenpingfeng 2017年2月9日
	 * 
	 * @param skuProductVO
	 * @param skuInfo
	 * @param request
	 * @param response
	 * @return 
	 * @deprecated
	 */
	@RequestMapping(value = "createProduct", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> createProduct(SkuProductVO skuProductVO,
			@RequestParam(value = "skuInfo", required = false) String skuInfo, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession();
			// 获取用户类型
			Integer userId = (Integer) session.getAttribute(WebConsts.USER_ID);
			Integer companyId = (Integer) session.getAttribute(WebConsts.COMPANY_ID);
			skuProductVO.setSkuUserId(userId);
			skuProductVO.setCompanyId(companyId);

			Integer skuBrandId = skuProductVO.getSkuBrandId();
			if (skuBrandId == null) {
				return new RestBody<String>(SkuResultCode.BRAND_NOT_EXISTS);
			}

			Result<String> result = skuProductManager.createSkuProduct(skuProductVO);
			if (!result.isSuccess()) {
				return new RestBody<String>(result.getCode(), result.getMessage());
			}
			String productCode = result.getDataModel();
			Result<SkuProductVO> resultSkuProductVO = skuProductManager.findProductByProductCode(productCode);
			SkuProductVO skuPro = resultSkuProductVO.getDataModel();
			// 根据companyId查询公司信息
			Result<SkuCompanyVO> resultCompany = skuCompanyManager.findSkuCompanyByCompanyId(companyId);
			if (!resultCompany.isSuccess()) {
				return new RestBody<String>(resultCompany.getCode(), resultCompany.getMessage());
			}
			SkuCompanyVO skuCompanyVO = resultCompany.getDataModel();
			skuPro.setCompanyName(skuCompanyVO.getCompanyName());

			Result<BrandVO> resultBrand = brandManager.getBrandById(skuPro.getSkuBrandId());
			BrandVO brandVO = resultBrand.getDataModel();
			if (brandVO != null) {
				skuPro.setBrandName(brandVO.getLabel());
			}

			// 设置图片列表
			List<String> pictures = skuProductVO.getPictures();
			if (pictures != null && pictures.size() > 0) {
				for (String picturePath : pictures) {
					ProductPicture productPicture = new ProductPicture();
					productPicture.setPicturePath(picturePath);
					productPicture.setProductId(skuPro.getProductId());
					Result<String> createProductPicture = productPictureManager.createProductPicture(productPicture);
					if (!createProductPicture.isSuccess()) {
						return new RestBody<String>(createProductPicture.getCode(), createProductPicture.getMessage());
					}
				}
			}
			// 添加sku属性关联表
			List<RelProductSkuAttribute> skuProducts = JSON.parseArray(skuInfo, RelProductSkuAttribute.class);
			if (skuProducts != null && skuProducts.size() > 0) {
				for (RelProductSkuAttribute relProductAkuAttribute : skuProducts) {
					relProductAkuAttribute.setProductId(skuPro.getProductId());
					skuProductManager.createProductSkuAttribute(relProductAkuAttribute);
				}
			}

			// 添加历史表

			SkuProduct skuProduct = SkuProductConverter.toSkuProduct(skuPro);
			Result<Integer> resultCreate = productDaoAdaptor.addHistory(skuProduct, session);
			if (!resultCreate.isSuccess()) {
				return new RestBody<String>(resultCreate.getCode(), resultCreate.getMessage());
			}

			// 根据productCode查询产品信息 生成mongodb数据
			MongoSkuProductVO mongoSkuProductVO = SkuProductConverter.toMongoSkuProductVO(skuPro);
			Integer productId = mongoSkuProductVO.getProductId();
			Result<List<RelProductSkuAttribute>> result2 = skuProductManager.selectByProductId(productId);
			List<RelProductSkuAttribute> relProductAkuAttributes = result2.getDataModel();
			Map<String, SkuItemAttributeVO> skus = new LinkedHashMap<String, SkuItemAttributeVO>();
			for (RelProductSkuAttribute rel : relProductAkuAttributes) {
				SkuItemAttributeVO skuItemAttributeVO = new SkuItemAttributeVO();
				skuItemAttributeVO.setSkuItemId(rel.getSkuItemId());
				skuItemAttributeVO.setValue(rel.getValue());
				skus.put(String.valueOf(rel.getSkuItemId()), skuItemAttributeVO);
			}
			mongoSkuProductVO.setSkus(skus);
			Result<String> resultSave = skuProductManager.save(mongoSkuProductVO);
			if (!resultSave.isSuccess()) {
				return new RestBody<String>(resultSave.getCode(), resultSave.getMessage());
			}
		} catch (Exception e) {
			LOGGER.error("create product {}", e);
			return new RestBody<String>(SkuResultCode.SYS_EXCEPTION);
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 
	 * 更新部品 2017年2月9日
	 * 
	 * @param skuProductVO
	 * @param skuInfo
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "updateProduct", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> updateProduct(SkuProductVO skuProductVO,
			@RequestParam(value = "skuInfo", required = false) String skuInfo, String pictures,
			HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();

		// 添加历史表
		try {
			Result<SkuProduct> resultSkuProduct = skuProductManager.findByProductId(skuProductVO.getProductId());
			if (!resultSkuProduct.isSuccess()) {
				return new RestBody<String>(resultSkuProduct.getCode(), resultSkuProduct.getMessage());
			}
			SkuProduct skuProduct = resultSkuProduct.getDataModel();

			Result<Integer> resultCreate = productDaoAdaptor.addHistory(skuProduct, session);
			if (!resultCreate.isSuccess()) {
				return new RestBody<String>(resultCreate.getCode(), resultCreate.getMessage());
			}
			// 更新
			skuProductVO.setThumbnail(skuProductVO.getPicturePath());
			if (skuProductVO.getAuditStatus() != null
					&& (skuProductVO.getAuditStatus().equals("1") || skuProductVO.getAuditStatus().equals("3"))) {
				skuProductVO.setAuditTime(new Date());
			}
			Result<String> result = skuProductManager.updateSkuProduct(skuProductVO);
			if (!result.isSuccess()) {
				return new RestBody<String>(result.getCode(), result.getMessage());
			}

			Result<SkuProduct> resultSkuProductVO = skuProductManager.findByProductId(skuProductVO.getProductId());
			SkuProduct skuPro = resultSkuProductVO.getDataModel();
			SkuProductVO skuProVO = SkuProductConverter.toSkuProductVO(skuPro);
			if (StringUtils.isNotBlank(skuInfo)) {
				List<RelProductSkuAttribute> skuProducts = JSON.parseArray(skuInfo, RelProductSkuAttribute.class);
				if (skuProducts.size() > 0) {
					for (RelProductSkuAttribute relProductAkuAttribute : skuProducts) {
						Result<String> resultUpdate = skuProductManager
								.updateProductSkuAttribute(relProductAkuAttribute);
						if (!resultUpdate.isSuccess()) {
							return new RestBody<String>(resultUpdate.getCode(), resultUpdate.getMessage());
						}
					}
				}
			}

			if (StringUtils.isNotBlank(pictures)) {
				List<ProductPictureVO> skuProducts = JSON.parseArray(pictures, ProductPictureVO.class);
				if (skuProducts != null && skuProducts.size() > 0) {
					for (ProductPictureVO picture : skuProducts) {
						Integer id = picture.getId();
						if (id == null) {
							ProductPicture productPicture = ProductPictureConverter.toProductPicture(picture);
							productPicture.setProductId(skuProductVO.getProductId());
							Result<String> cResult = productPictureManager.createProductPicture(productPicture);
							if (!cResult.isSuccess()) {
								return new RestBody<String>(cResult.getCode(), cResult.getMessage());
							}
						} else {
							// 更新
							Result<String> uResult = productPictureManager.updateProductPicture(picture);
							if (!uResult.isSuccess()) {
								return new RestBody<String>(uResult.getCode(), uResult.getMessage());
							}
						}
					}
				}
			}

			// 根据productCode查询产品信息 生成mongodb数据
			skuProductManager.deleteProductByMongoDB(skuProductVO.getProductId());// 删除mongodb数据

			Result<SkuCompanyVO> resultCompany = skuCompanyManager.findSkuCompanyByCompanyId(skuProVO.getCompanyId());
			SkuCompanyVO skuCompanyVO = resultCompany.getDataModel();
			skuProVO.setCompanyName(skuCompanyVO.getCompanyName());

			Result<BrandVO> resultBrand = brandManager.getBrandById(skuProVO.getSkuBrandId());
			BrandVO brandVO = resultBrand.getDataModel();
			if (brandVO != null) {
				skuProVO.setBrandName(brandVO.getLabel());
			}
			Result<Integer> strategicSkuItemIdRes = skuItemManager.getStrategicSkuItemId(skuProduct.getSkuCategoryId());
			Integer strategicSkuItemId = null;
			if (strategicSkuItemIdRes.isSuccess()) {
				strategicSkuItemId = strategicSkuItemIdRes.getDataModel();
			}

			MongoSkuProductVO mongoSkuProductVO = SkuProductConverter.toMongoSkuProductVO(skuProVO);
			Integer productId = mongoSkuProductVO.getProductId();
			Result<List<RelProductSkuAttribute>> result2 = skuProductManager.selectByProductId(productId);
			List<RelProductSkuAttribute> relProductAkuAttributes = result2.getDataModel();
			Map<String, SkuItemAttributeVO> skus = new LinkedHashMap<String, SkuItemAttributeVO>();
			for (RelProductSkuAttribute rel : relProductAkuAttributes) {
				SkuItemAttributeVO skuItemAttributeVO = new SkuItemAttributeVO();
				skuItemAttributeVO.setSkuItemId(rel.getSkuItemId());
				skuItemAttributeVO.setValue(rel.getValue());
				skus.put(String.valueOf(rel.getSkuItemId()), skuItemAttributeVO);
				if(rel.getSkuItemId().equals(strategicSkuItemId)){
					mongoSkuProductVO.setStrategicPrice(Double.valueOf(rel.getValue()));
				}
			}
			mongoSkuProductVO.setSkus(skus);

			Result<String> resultSave = skuProductManager.save(mongoSkuProductVO);
			if (!resultSave.isSuccess()) {
				return new RestBody<String>(resultSave.getCode(), resultSave.getMessage());
			}
		} catch (Exception e) {
			LOGGER.error("updateProduct Exception {}", e);
			return new RestBody<String>(SkuResultCode.SYS_EXCEPTION);
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 批量审批 shenpingfeng 2017年2月27日
	 * 
	 * @param skuProducts
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "approve", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> approve(String skuProducts, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {

		if (StringUtils.isBlank(skuProducts)) {
			return new RestBody<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<SkuProductVO> skuProductVOs = JSON.parseArray(skuProducts, SkuProductVO.class);
		if (skuProductVOs != null && skuProductVOs.size() > 0) {
			for (SkuProductVO skuProductVO : skuProductVOs) {
				// 添加历史表
				try {
					Result<SkuProduct> resultSkuProduct = skuProductManager
							.findByProductId(skuProductVO.getProductId());
					if (!resultSkuProduct.isSuccess()) {
						return new RestBody<String>(resultSkuProduct.getCode(), resultSkuProduct.getMessage());
					}
					SkuProduct skuProduct = resultSkuProduct.getDataModel();

					Result<Integer> resultCreate = productDaoAdaptor.addHistory(skuProduct, session);
					if (!resultCreate.isSuccess()) {
						return new RestBody<String>(resultCreate.getCode(), resultCreate.getMessage());
					}
					// 更新
					skuProductVO.setThumbnail(skuProductVO.getPicturePath());
					if (skuProductVO.getAuditStatus() != null && (skuProductVO.getAuditStatus().equals("1")
							|| skuProductVO.getAuditStatus().equals("3"))) {
						skuProductVO.setAuditTime(new Date());
					} else {
						return new RestBody<String>(SkuResultCode.NO_PERMISSION);
					}
					Result<String> result = skuProductManager.updateSkuProduct(skuProductVO);
					if (!result.isSuccess()) {
						return new RestBody<String>(result.getCode(), result.getMessage());
					}

					Result<SkuProduct> resultSkuProductVO = skuProductManager
							.findByProductId(skuProductVO.getProductId());
					SkuProduct skuPro = resultSkuProductVO.getDataModel();
					SkuProductVO skuProVO = SkuProductConverter.toSkuProductVO(skuPro);

					// 根据productCode查询产品信息 生成mongodb数据
					skuProductManager.deleteProductByMongoDB(skuProductVO.getProductId());// 删除mongodb数据

					Result<SkuCompanyVO> resultCompany = skuCompanyManager
							.findSkuCompanyByCompanyId(skuProVO.getCompanyId());
					SkuCompanyVO skuCompanyVO = resultCompany.getDataModel();
					skuProVO.setCompanyName(skuCompanyVO.getCompanyName());

					Result<BrandVO> resultBrand = brandManager.getBrandById(skuProVO.getSkuBrandId());
					BrandVO brandVO = resultBrand.getDataModel();
					if (brandVO != null) {
						skuProVO.setBrandName(brandVO.getLabel());
					}
					MongoSkuProductVO mongoSkuProductVO = SkuProductConverter.toMongoSkuProductVO(skuProVO);
					Integer productId = mongoSkuProductVO.getProductId();
					Result<List<RelProductSkuAttribute>> result2 = skuProductManager.selectByProductId(productId);
					List<RelProductSkuAttribute> relProductAkuAttributes = result2.getDataModel();
					Map<String, SkuItemAttributeVO> skus = new LinkedHashMap<String, SkuItemAttributeVO>();
					for (RelProductSkuAttribute rel : relProductAkuAttributes) {
						SkuItemAttributeVO skuItemAttributeVO = new SkuItemAttributeVO();
						skuItemAttributeVO.setSkuItemId(rel.getSkuItemId());
						skuItemAttributeVO.setValue(rel.getValue());
						skus.put(String.valueOf(rel.getSkuItemId()), skuItemAttributeVO);
					}
					mongoSkuProductVO.setSkus(skus);

					Result<String> resultSave = skuProductManager.save(mongoSkuProductVO);
					if (!resultSave.isSuccess()) {
						return new RestBody<String>(resultSave.getCode(), resultSave.getMessage());
					}
				} catch (Exception e) {
					LOGGER.error("updateProduct Exception {}", e);
					return new RestBody<String>(SkuResultCode.SYS_EXCEPTION);
				}
			}
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 新增图片 shenpingfeng 2016年12月5日
	 * 
	 * @param pictures
	 * @param productId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "createProductPicture", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> createProductPicture(String[] pictures, Integer productId, HttpServletRequest request,
			HttpServletResponse response) {
		if (pictures != null && pictures.length > 0) {
			for (String picturePath : pictures) {
				ProductPicture productPicture = new ProductPicture();
				productPicture.setPicturePath(picturePath);
				productPicture.setProductId(productId);
				Result<String> createProductPicture = productPictureManager.createProductPicture(productPicture);
				if (!createProductPicture.isSuccess()) {
					return new RestBody<String>(createProductPicture.getCode(), createProductPicture.getMessage());
				}
			}
		}
		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 删除图片 shenpingfeng 2016年12月5日
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "deleteProductPicture", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> deleteProductPicture(Integer id, HttpServletRequest request, HttpServletResponse response) {

		Result<String> result = productPictureManager.deleteProductPicture(id);
		if (!result.isSuccess()) {
			return new RestBody<String>(result.getCode(), result.getMessage());
		}
		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 查询sku信息 shenpingfeng 2016年12月7日
	 * 
	 * @param skuCategoryId
	 * @return
	 */
	@RequestMapping(value = "querySkuItem", method = RequestMethod.GET)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public RestBody<Map<String, Object>> querySkuItem(Integer skuCategoryId, Integer productId) {

		Result<Map<String, Object>> result = skuItemManager.getSkuByCategoryId(skuCategoryId);
        if (!result.isSuccess()) {
			return new RestBody<Map<String, Object>>(result.getCode(), result.getMessage());
		}
		List<SkuItemBasicVO> skuItemBasicVOs = (List<SkuItemBasicVO>) result.getDataModel().get("skuItemNotOptionVOs");
		for (SkuItemBasicVO skuItemBasicVO : skuItemBasicVOs) {
			SkuItemVO skuItemVO = skuItemBasicVO.getSkuItemVO();
			Integer id = skuItemVO.getId();
			Result<RelProductSkuAttribute> resultRel = skuProductManager
					.findProductSkuAttributeByProductIdAndSkuItemId(productId, id);
			if (resultRel.isSuccess()) {
				RelProductSkuAttribute relProductAkuAttribute = resultRel.getDataModel();
				String value = relProductAkuAttribute.getValue();
				Integer productSkuAttributeId = relProductAkuAttribute.getId();
				skuItemVO.setValue(value);
				skuItemVO.setProductSkuAttributeId(productSkuAttributeId);
			}
		}
		Map<String, List<SkuItemAttribute>> optionItemMap = (Map<String, List<SkuItemAttribute>>) result.getDataModel().get
				("optionItemMap");
		for (String key : optionItemMap.keySet()) {
			List<SkuItemAttribute> skuItemAttributeList = optionItemMap.get(key);
			Result<RelProductSkuAttribute> resultRel = skuProductManager.findProductSkuAttributeByProductIdAndSkuItemId
					(productId, skuItemAttributeList.get(0).getSkuItemId());
			if (resultRel.isSuccess()) {
				RelProductSkuAttribute relProductAkuAttribute = resultRel.getDataModel();
				Integer productSkuAttributeId = relProductAkuAttribute.getId();
				for (SkuItemAttribute skuItemAttribute : skuItemAttributeList) {
					skuItemAttribute.setProductSkuAttributeId(productSkuAttributeId);
				}
			}
		}

		return new RestBody<Map<String, Object>>(SkuResultCode.SUCCESS, result.getDataModel());
	}

	/**
	 * 查询sku属性 shenpingfeng 2016年12月7日
	 * 
	 * @param skuItemId
	 * @return
	 */
	@RequestMapping(value = "querySkuItemAttribute", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<List<SkuItemAttribute>> querySkuItemAttribute(Integer skuItemId) {

		Result<List<SkuItemAttribute>> result = skuItemManager.getSkuItemAttributeBySkuItemId(skuItemId);
		if (!result.isSuccess()) {
			return new RestBody<List<SkuItemAttribute>>(result.getCode(), result.getMessage());
		}
		return new RestBody<List<SkuItemAttribute>>(SkuResultCode.SUCCESS, result.getDataModel());
	}

	public Result<List<Integer>> getSkuRoleId(HttpServletRequest request) {
		// 获取当前登录人的角色
		HttpSession session = request.getSession();
		Integer userId = (Integer) session.getAttribute(WebConsts.USER_ID);
		Result<List<Integer>> resultSkuRoleIds = userRoleManager.findByUserId(userId);
		return resultSkuRoleIds;
	}

	public Result<RolePrice> getRolePrice(Integer skuRoleId) {
		Result<RolePrice> resultRolePrice = rolePriceManager.getRolePriceBySkuRoleId(skuRoleId);
		return resultRolePrice;
	}

	/**
	 * 刪除 shenpingfeng 2016年12月19日
	 * 
	 * @param skuProducts
	 * @return
	 */
	@RequestMapping(value = "deleteProduct", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> deleteProduct(String skuProducts) {
		if (StringUtils.isBlank(skuProducts)) {
			return new RestBody<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<SkuProduct> skuProductList = JSON.parseArray(skuProducts, SkuProduct.class);
		if (skuProductList != null && skuProductList.size() > 0) {
			for (SkuProduct skuProduct : skuProductList) {
				Result<String> result = skuProductManager.deleteSkuProduct(skuProduct);
				if (!result.isSuccess()) {
					return new RestBody<String>(result.getCode(), result.getMessage());
				}
			}
		}
		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 创建excel模板 shenpingfeng 2016年12月22日
	 * 
	 * @param categoryId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public RestBody<Map<String, String>> create(Integer categoryId, HttpServletRequest request) {

		Map<String, String> retMap = new HashMap<>();
		Result<Map<String, Object>> result = skuItemManager.getSkuByCategoryId(categoryId);
		List<SkuItemBasicVO> skuItemBasicVOs = null;
		if (result.isSuccess()) {
			skuItemBasicVOs = (List<SkuItemBasicVO>)result.getDataModel().get("skuItemBasicVOs");
		}
		Result<Category> resultCategory = categoryManager.getCagegorysById(categoryId);
		Category category = resultCategory.getDataModel();

		Map<String, List<String>> skuAttribute = new HashMap<>();
		List<String> fieldName = new ArrayList<String>();
		fieldName.add("产品名称");
		fieldName.add("型号");
		fieldName.add("价格 ");
		fieldName.add("产地");
		fieldName.add("图片");
		fieldName.add("详情");
		fieldName.add("售后维保");

		if (skuItemBasicVOs != null && skuItemBasicVOs.size() > 0) {
			for (SkuItemBasicVO skuItemBasicVO : skuItemBasicVOs) {
				SkuItemVO skuItemVO = skuItemBasicVO.getSkuItemVO();
				fieldName.add(skuItemVO.getSkuName());
				List<SkuItemAttributeVO> skuItemAttributeVOs = skuItemBasicVO.getSkuItemAttributeVOs();
				List<String> skuItemAttributes = new ArrayList<>();
				if (skuItemAttributeVOs != null && skuItemAttributeVOs.size() > 0) {
					for (SkuItemAttributeVO skuItemAttributeVO : skuItemAttributeVOs) {
						skuItemAttributes.add(skuItemAttributeVO.getValue());
					}
					skuAttribute.put(skuItemVO.getSkuName(), skuItemAttributes);
				}
			}
		}

		try {
			String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
			// 项目的根目录路径
			String projectPath = nodepath.substring(1, nodepath.length() - 16);
			ProductToExcel ef = new ProductToExcel(fieldName, skuAttribute);
			String filePath = "/" + projectPath + "/static/" + category.getLabel() + ".xls";
			File file = new File(filePath);
			LOGGER.info("file path {}", filePath);
			if (!file.isFile()) {
				file.createNewFile();
			}
			ef.exportExcel(new FileOutputStream(file));
			retMap.put("fileName", category.getLabel() + ".xls");

		} catch (Exception e) {
			LOGGER.error("create exception {}", e);
			return new RestBody<Map<String, String>>(SkuResultCode.SYS_EXCEPTION);
		}
		return new RestBody<Map<String, String>>(SkuResultCode.SUCCESS, retMap);

	}

	/**
	 * 解析excel文件 shenpingfeng 2016年12月22日
	 * 
	 * @param multipartFile
	 * @param categoryId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "import", method = RequestMethod.POST)
	@ResponseBody
	@SuppressWarnings("unchecked")
	public RestBody<List<SkuProductVO>> excelImport(MultipartFile multipartFile, String action, Integer categoryId,
			HttpSession session) {

		Result<Map<String, Object>> result = skuItemManager.getSkuByCategoryId(categoryId);
		List<SkuItemBasicVO> skuItemBasicVOs = null;
		if (result.isSuccess()) {
			skuItemBasicVOs = (List<SkuItemBasicVO>)result.getDataModel().get("skuItemBasicVOs");
		}

		if (skuItemBasicVOs == null) {
			skuItemBasicVOs = new ArrayList<SkuItemBasicVO>();
		}

		List<String> fieldName = new ArrayList<String>();

		for (SkuItemBasicVO skuItemBasicVO : skuItemBasicVOs) {
			SkuItemVO skuItemVO = skuItemBasicVO.getSkuItemVO();
			fieldName.add(skuItemVO.getSkuName());
		}
		Result<List<SkuProductVO>> resultSkuProduct = ReadExcelUtil.createProduct(multipartFile, fieldName, session);
		if (!resultSkuProduct.isSuccess()) {
			return new RestBody<List<SkuProductVO>>(resultSkuProduct.getCode(), resultSkuProduct.getMessage());
		}
		List<SkuProductVO> skuProductVOs = resultSkuProduct.getDataModel();
		for (SkuProductVO skuProductVO : skuProductVOs) {
			Map<String, PictureData> sheetPictrues = skuProductVO.getSheetPictrues();
			Map<String, PictureData> detailPictrues = skuProductVO.getDetailPictrues();

			if (sheetPictrues != null && sheetPictrues.size() > 0) {
				List<String> pictures = new LinkedList<>();
				Object key[] = sheetPictrues.keySet().toArray();

				for (int i = 0; i < sheetPictrues.size(); i++) {
					// 获取图片流
					PictureData pic = sheetPictrues.get(key[i]);
					String mimeType = pic.getMimeType();

					String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
					String projectPath = nodepath.substring(1, nodepath.length() - 16);
					String filePath = "/" + projectPath + "/static/" + "picture" + ".xls";
					File file = new File(filePath);
					try {
						FileUtils.writeByteArrayToFile(file, pic.getData());
						Result<String> resultCreatePic = skuProductManager.uploadedFileUpdate(file, mimeType);
						LOGGER.info("resultCreatePic {}", resultCreatePic.isSuccess());
						if (!resultCreatePic.isSuccess()) {
							return new RestBody<>(resultCreatePic.getCode(), resultCreatePic.getMessage());
						}
						String picturePath = resultCreatePic.getDataModel();
						if (i == 0) {
							skuProductVO.setPicturePath(picturePath);
						} else {
							pictures.add(picturePath);
						}
						skuProductVO.setPictures(pictures);

					} catch (Exception e) {
						LOGGER.error("upload file exception {}", e);
					}
				}
			}
			skuProductVO.setSheetPictrues(null);

			List<String> picturePaths = new LinkedList<>();
			Map<String, Object> detailMap = new LinkedHashMap<>();
			if (StringUtils.isNotBlank(skuProductVO.getDescription())) {
				detailMap.put("text", skuProductVO.getDescription());
			}
			if (detailPictrues != null && detailPictrues.size() > 0) {
				for (String key : detailPictrues.keySet()) {
					PictureData pic = detailPictrues.get(key);
					String mimeType = pic.getMimeType();

					String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
					String projectPath = nodepath.substring(1, nodepath.length() - 16);
					String filePath = "/" + projectPath + "/static/" + "picture" + ".xls";
					File file = new File(filePath);
					try {
						FileUtils.writeByteArrayToFile(file, pic.getData());
						Result<String> resultCreatePic = skuProductManager.uploadedFileUpdate(file, mimeType);
						LOGGER.info("resultCreatePic {}", resultCreatePic.isSuccess());
						if (!resultCreatePic.isSuccess()) {
							return new RestBody<>(resultCreatePic.getCode(), resultCreatePic.getMessage());
						}
						String picturePath = resultCreatePic.getDataModel();
						picturePaths.add(picturePath);
					} catch (Exception e) {
						LOGGER.error("upload file exception {}", e);
					}
				}
				detailMap.put("pictrues", picturePaths);
			}
			if (detailMap.size() > 0) {
				skuProductVO.setDescription(JSONObject.toJSONString(detailMap));
			}
			skuProductVO.setDetailPictrues(null);
		}
		if (skuItemBasicVOs.size() > 0) {
			for (SkuProductVO skuProductVO : skuProductVOs) {
				Map<String, SkuItemAttributeVO> skus = skuProductVO.getSkus();
				for (String key : skus.keySet()) {
					SkuItemAttributeVO skuItemAttributeVO = skus.get(key);
					String value = skuItemAttributeVO.getValue();
					for (SkuItemBasicVO skuItemBasicVO : skuItemBasicVOs) {
						SkuItemVO skuItemVO = skuItemBasicVO.getSkuItemVO();
						String isRequired = skuItemVO.getIsRequired();

						List<SkuItemAttributeVO> skuItemAttributeVOs = skuItemBasicVO.getSkuItemAttributeVOs();
						LOGGER.info("skuItemAttributeVOs {}", skuItemAttributeVOs);
						String title = skuItemVO.getTitle();
						if (key.equals(title) && skuItemAttributeVOs != null & "0".equals(skuItemVO.getValueType())) {
							Boolean flag = false;
							for (SkuItemAttributeVO itemAttributeVO : skuItemAttributeVOs) {
								if (StringUtils.isBlank(value)) {
									if (isRequired.equals(IsRequired.YES.getValue())) {
										return new RestBody<List<SkuProductVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
									}
									flag = true;
									break;
								}
								String value2 = itemAttributeVO.getValue();
								if (value.equals(value2)) {
									flag = true;
									break;
								}
							}
							if (!flag) {
								return new RestBody<List<SkuProductVO>>(SkuResultCode.SKU_ITEM_ATTRIBUTE_NOT_EXIST);
							}

						}
					}
				}
			}
		}

		for (SkuProductVO skuProductVO : skuProductVOs) {
			Map<String, SkuItemAttributeVO> skus = skuProductVO.getSkus();
			if (skus != null && skus.size() > 0) {
				for (String key : skus.keySet()) {
					SkuItemAttributeVO skuItemAttributeVO = skus.get(key);
					for (SkuItemBasicVO skuItemBasicVO : skuItemBasicVOs) {
						SkuItemVO skuItemVO = skuItemBasicVO.getSkuItemVO();
						String skuName = skuItemVO.getSkuName();
						if (key.equals(skuName)) {
							skuItemAttributeVO.setSkuItemId(skuItemVO.getId());
						}
					}
				}
			}
		}

		return new RestBody<List<SkuProductVO>>(SkuResultCode.SUCCESS, skuProductVOs);
	}

	/**
	 * 批量创建产品 shenpingfeng 2016年12月20日
	 * 
	 * @param skuProductVOs
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "createProductList", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> createProductList(String skuProductVOs, HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession();
			if (StringUtils.isBlank(skuProductVOs)) {
				return new RestBody<>(SkuResultCode.PARAMETER_NOT_EMPTY);
			}
			List<SkuProductVO> skuProductVOList = JSON.parseArray(skuProductVOs, SkuProductVO.class);
			if (skuProductVOList == null || skuProductVOList.size() == 0) {
				return new RestBody<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
			}
			for (SkuProductVO skuProductVO : skuProductVOList) {
				// 判断品牌是否存在 如果不存在提示错误信息
				Integer skuBrandId = skuProductVO.getSkuBrandId();
				if (skuBrandId == null) {
					return new RestBody<String>(SkuResultCode.BRAND_NOT_EXISTS);
				}

				String skuInfo = skuProductVO.getSkuInfo();
				// 获取用户类型
				Integer userId = (Integer) session.getAttribute(WebConsts.USER_ID);
				Integer companyId = (Integer) session.getAttribute(WebConsts.COMPANY_ID);
				skuProductVO.setSkuUserId(userId);
				skuProductVO.setCompanyId(companyId);

				Result<String> result = skuProductManager.createSkuProduct(skuProductVO);
				if (!result.isSuccess()) {
					return new RestBody<String>(result.getCode(), result.getMessage());
				}
				String productCode = result.getDataModel();
				Result<SkuProductVO> resultSkuProductVO = skuProductManager.findProductByProductCode(productCode);
				SkuProductVO skuPro = resultSkuProductVO.getDataModel();

				// 根据companyId查询公司信息
				Result<SkuCompanyVO> resultCompany = skuCompanyManager.findSkuCompanyByCompanyId(companyId);
				if (!resultCompany.isSuccess()) {
					return new RestBody<String>(resultCompany.getCode(), resultCompany.getMessage());
				}
				SkuCompanyVO skuCompanyVO = resultCompany.getDataModel();
				skuPro.setCompanyName(skuCompanyVO.getCompanyName());

				Result<BrandVO> resultBrand = brandManager.getBrandById(skuPro.getSkuBrandId());
				BrandVO brandVO = resultBrand.getDataModel();
				if (brandVO != null) {
					skuPro.setBrandName(brandVO.getLabel());
				}

				// 设置图片列表
				List<String> pictures = skuProductVO.getPictures();
				if (pictures != null && pictures.size() > 0) {
					for (String picturePath : pictures) {
						ProductPicture productPicture = new ProductPicture();
						productPicture.setPicturePath(picturePath);
						productPicture.setProductId(skuPro.getProductId());
						Result<String> createProductPicture = productPictureManager
								.createProductPicture(productPicture);
						if (!createProductPicture.isSuccess()) {
							return new RestBody<String>(createProductPicture.getCode(),
									createProductPicture.getMessage());
						}
					}
				}
				// 添加sku属性关联表

				List<RelProductSkuAttribute> skuProducts = JSON.parseArray(skuInfo, RelProductSkuAttribute.class);
				if (skuProducts != null && skuProducts.size() > 0) {
					for (RelProductSkuAttribute relProductAkuAttribute : skuProducts) {
						relProductAkuAttribute.setProductId(skuPro.getProductId());
						skuProductManager.createProductSkuAttribute(relProductAkuAttribute);
					}
				}

				// 添加历史表
				SkuProduct skuProduct = SkuProductConverter.toSkuProduct(skuPro);
				Result<Integer> resultCreate = productDaoAdaptor.addHistory(skuProduct, session);
				if (!resultCreate.isSuccess()) {
					return new RestBody<String>(resultCreate.getCode(), resultCreate.getMessage());
				}

				Result<Integer> strategicSkuItemIdRes = skuItemManager.getStrategicSkuItemId(skuProduct.getSkuCategoryId());
				Integer strategicSkuItemId = null;
				if (strategicSkuItemIdRes.isSuccess()) {
					strategicSkuItemId = strategicSkuItemIdRes.getDataModel();
				}
				// 根据productCode查询产品信息 生成mongodb数据
				MongoSkuProductVO mongoSkuProductVO = SkuProductConverter.toMongoSkuProductVO(skuPro);
				Integer productId = mongoSkuProductVO.getProductId();
				Result<List<RelProductSkuAttribute>> result2 = skuProductManager.selectByProductId(productId);
				List<RelProductSkuAttribute> relProductAkuAttributes = result2.getDataModel();
				Map<String, SkuItemAttributeVO> skus = new LinkedHashMap<String, SkuItemAttributeVO>();
				for (RelProductSkuAttribute rel : relProductAkuAttributes) {
					SkuItemAttributeVO skuItemAttributeVO = new SkuItemAttributeVO();
					skuItemAttributeVO.setSkuItemId(rel.getSkuItemId());
					skuItemAttributeVO.setValue(rel.getValue());
					skus.put(String.valueOf(rel.getSkuItemId()), skuItemAttributeVO);
					if(rel.getSkuItemId().equals(strategicSkuItemId)){
						mongoSkuProductVO.setStrategicPrice(Double.valueOf(rel.getValue()));
					}
				}
				mongoSkuProductVO.setSkus(skus);
				Result<String> resultSave = skuProductManager.save(mongoSkuProductVO);
				if (!resultSave.isSuccess()) {
					return new RestBody<String>(resultSave.getCode(), resultSave.getMessage());
				}
			}

		} catch (Exception e) {
			LOGGER.error("createProductList {}", e);
			return new RestBody<String>(SkuResultCode.SYS_EXCEPTION);
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	public static String ReadFile(String Path) {
		BufferedReader reader = null;
		String laststr = "";
		try {
			FileInputStream fileInputStream = new FileInputStream(Path);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				laststr += tempString;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return laststr;
	}

	/**
	 * 推荐 shenpingfeng 2017年2月27日
	 * 
	 * @param skuProductQueryVO
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "commend", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<List<SkuProductVO>> commend(SkuProductQueryVO skuProductQueryVO, HttpServletRequest request,
			HttpServletResponse response) {
		Result<List<SkuProductVO>> result = skuProductManager.getProductByStatement(skuProductQueryVO);
		if (!result.isSuccess()) {
			return new RestBody<List<SkuProductVO>>(result.getCode(), result.getMessage());
		}

		return new RestBody<List<SkuProductVO>>(SkuResultCode.SUCCESS, result.getDataModel());
	}
	
	
	@RequestMapping(value = "queryProductCollections", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<List<SkuProductVO>> queryProductCollections(SkuProductQueryVO skuProductQueryVO, HttpServletRequest request,
			HttpServletResponse response) {
		Result<List<SkuProductVO>> result = skuProductManager.getProductByStatement(skuProductQueryVO);
		if (!result.isSuccess()) {
			return new RestBody<List<SkuProductVO>>(result.getCode(), result.getMessage());
		}

		return new RestBody<List<SkuProductVO>>(SkuResultCode.SUCCESS, result.getDataModel());
	}

	@RequestMapping(value = "queryOptionItemIds", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<List<String>> queryOptionItemIds(Integer itemId) {
		Result<List<String>> result = skuItemManager.getOptionItemNumber(itemId);
		if (!result.isSuccess()) {
			return new RestBody<List<String>>(result.getCode(), result.getMessage());
		}

		return new RestBody<List<String>>(SkuResultCode.SUCCESS, result.getDataModel());
	}

	@RequestMapping(value = "list1")
	public String test() {

		return "product/list";
	}
	
	
}
